package com.example.demovalidator.web;

import com.example.demovalidator.Vo.ResultVo;
import com.example.demovalidator.enums.ErrorCode;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author lxw
 * @date 2021/8/9
 * @apiNote
 */
@ControllerAdvice
@ResponseBody
public class CtrIAdvice {

    @ExceptionHandler
    public ResultVo exceptionHandler(MethodArgumentNotValidException e){
        Map<String, String> collect = e.getBindingResult().getFieldErrors().stream()
                .collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
        return ResultVo.fail(ErrorCode.PARAM_ERROR,collect);
    }
}
